package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void taskOrderStatus()
    {
        log.info("开始处理超时订单");
        //检查超时订单
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> task =  orderMapper.selectByStatusAndTime(Orders.PAID,time);

        if (task != null && task.size() > 0)
        {
            task.forEach(item ->{
                item.setStatus(Orders.CANCELLED);
                item.setCancelReason("订单超时，自动取消");
                item.setCancelTime(LocalDateTime.now());
                orderMapper.update(item);
            });
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder()
    {
        log.info("开始处理派送中订单");
        //检查超时订单
        LocalDateTime time = LocalDateTime.now().minusHours(2);
        List<Orders> task =  orderMapper.selectByStatusAndTime(Orders.DELIVERY_IN_PROGRESS,time);

        if (task != null && task.size() > 0)
        {
            task.forEach(item ->{
                item.setStatus(Orders.COMPLETED);
                item.setDeliveryTime(time);
                orderMapper.update(item);
            });
        }
    }


}
